const path = require("path");
const express = require("express");
const contentListM = require("./db/collections/contentList");
const {getNowTime} = require("./utils");
const middleware = require("./middleware");
const app = express();
app.use(function(req,res,next){
	res.set("Access-Control-Allow-Origin","*");
	res.set("Access-Control-Allow-Headers","*");
	res.set("Access-Control-Allow-Methods","*");
	next();
})
app.use(express.static(path.resolve(__dirname,"../")));
app.use(express.json());
app.use(middleware.sendJson())
// 添加微博
app.post("/weibo",async (req,res)=>{
	try{
		const {content} = req.body;
		const count = await contentListM.count({content});
		if(count > 0) res.sendJson("您提交的内容已经存在，请不要重复提交");
		else{
			await contentListM.insertOne({
				content,
				addTime:getNowTime()
			})
			res.sendJson("添加成功",1);
		}
	}catch (err){
		console.log(err);
		res.sendJson()
	}
})
// 获取微博
app.get("/weibo",async (req,res)=>{
	try{
		// pageNo:页码
		let pageNo = (req.query.pageNo || 1)/1;
		// pageSize:每页显示的条数
		const pageSize = (req.query.pageSize || 1)/1;
		// 总条数
		const count = await contentListM.count();
		// 求总页数
		let pageSum = Math.ceil(count/pageSize);
		if(pageSum<1) pageSum = 1;
		if(pageNo < 1) pageNo = 1;
		if(pageNo >pageSum) pageNo = pageSum;
		
		const contentList = await contentListM.find({
			sortObj:{
				addTime:-1,// 按时间倒序排列
			},
			limit:pageSize,
			skip:(pageNo-1)*pageSize
		})
		res.json({
			ok:1,
			contentList,
			pageSum,
			pageNo
		})
	}catch (err){
		console.log(err);
		res.sendJson();
	}
	
})
// 修改微博
app.put("/weibo/:id/:type",async (req,res)=>{
	try{
		const {id,type} = req.params;
		// type 1:顶 2：踩
		// await contentListM.updateOneById(id,{
		// 	$inc:{
		// 		[type/1===1?"topNum":"downNum"]:1
		// 	}
		// })
		
		let $inc = {topNum:1}
		if(type/1 === 2) $inc = {downNum:1}
		await contentListM.updateOneById(id,{$inc});
		res.sendJson("修改成功",1);
	}catch (err){
		console.log(err);
		res.sendJson();
	}
})
// 删除微博
app.delete("/weibo/:id",async (req,res)=>{
	try{
		const {id} = req.params;
		await contentListM.deleteOneById(id);
		res.sendJson("删除成功",1);
	}catch (err){
		console.log(err);
		res.sendJson();
	}
	
})


app.listen(80,()=>{
	console.log("success");
})